<!DOCTYPE html>
<html>
<head>
    

    

    
<!-- Baidu Tongji -->
<script>var _hmt = _hmt || []</script>
<script async src="//hm.baidu.com/hm.js?ca9f046e770c921a4fd9535af2bb011a"></script>
<!-- End Baidu Tongji -->




    <meta charset="utf-8">
    
    
    
    <link rel="canonical" href="true/weblog/2018/09/29/ImageResizer/">
    
    
    <title>前端JS 图片压缩 | Greg&#39;s Blog | 今天也要加油鸭.jpg</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    
    <meta name="theme-color" content="#3F51B5">
    
    
    <meta name="keywords" content="HTML,jQuery">
    <meta name="description" content="使用js原生上传图片，先将图片转为base64格式数据；然后初始化自定义对象ImageResizer，传入最大高宽、图片base64等参数；在ImageResizer中，先把图片对象写入到canvas中，然后根据最大高宽按原图片高宽比等比例缩小；最后返回缩小后的base64数据和canvas。">
<meta name="keywords" content="HTML,jQuery">
<meta property="og:type" content="article">
<meta property="og:title" content="前端JS 图片压缩">
<meta property="og:url" content="https://greg0566.gitee.io/weblog/2018/09/29/ImageResizer/index.html">
<meta property="og:site_name" content="Greg&#39;s Blog">
<meta property="og:description" content="使用js原生上传图片，先将图片转为base64格式数据；然后初始化自定义对象ImageResizer，传入最大高宽、图片base64等参数；在ImageResizer中，先把图片对象写入到canvas中，然后根据最大高宽按原图片高宽比等比例缩小；最后返回缩小后的base64数据和canvas。">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2018-09-29T15:28:56.187Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="前端JS 图片压缩">
<meta name="twitter:description" content="使用js原生上传图片，先将图片转为base64格式数据；然后初始化自定义对象ImageResizer，传入最大高宽、图片base64等参数；在ImageResizer中，先把图片对象写入到canvas中，然后根据最大高宽按原图片高宽比等比例缩小；最后返回缩小后的base64数据和canvas。">
    
        <link rel="alternate" type="application/atom+xml" title="Greg&#39;s Blog" href="/weblog/atom.xml">
    
    <link rel="shortcut icon" href="/weblog/duck.png">
    <link rel="stylesheet" href="/weblog/css/style.css?v=1.7.2">
    <script>window.lazyScripts=[]</script>

    <!-- custom head -->
    

</head>

<body>
    <div id="loading" class="active"></div>

    <aside id="menu" class="hide" >
  <div class="inner flex-row-vertical">
    <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menu-off">
        <i class="icon icon-lg icon-close"></i>
    </a>
    <div class="brand-wrap" style="background-image:url(/weblog/img/brand.jpg)">
      <div class="brand">
        <a href="/weblog/" class="avatar waves-effect waves-circle waves-light">
          <img src="/weblog/img/head.jpg">
        </a>
        <hgroup class="introduce">
          <h5 class="nickname">Greg Zhou</h5>
          <a href="mailto:zhourikai@imperial-vision.com" title="zhourikai@imperial-vision.com" class="mail">zhourikai@imperial-vision.com</a>
        </hgroup>
      </div>
    </div>
    <div class="scroll-wrap flex-col">
      <ul class="nav">
        
            <li class="waves-block waves-effect">
              <a href="/weblog/"  >
                <i class="icon icon-lg icon-home"></i>
                主页
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/weblog/archives"  >
                <i class="icon icon-lg icon-archives"></i>
                编年史
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/weblog/tags"  >
                <i class="icon icon-lg icon-tags"></i>
                标签
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://github.com/zhourikai2008" target="_blank" >
                <i class="icon icon-lg icon-github"></i>
                Github
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://wuyukangkang.gitee.io/blog" target="_blank" >
                <i class="icon icon-lg icon-location-arrow"></i>
                友情链接 - 康康大神
              </a>
            </li>
        
      </ul>
    </div>
  </div>
</aside>

    <main id="main">
        <header class="top-header" id="header">
    <div class="flex-row">
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light on" id="menu-toggle">
          <i class="icon icon-lg icon-navicon"></i>
        </a>
        <div class="flex-col header-title ellipsis">前端JS 图片压缩</div>
        
        <div class="search-wrap" id="search-wrap">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="back">
                <i class="icon icon-lg icon-chevron-left"></i>
            </a>
            <input type="text" id="key" class="search-input" autocomplete="off" placeholder="输入感兴趣的关键字">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="search">
                <i class="icon icon-lg icon-search"></i>
            </a>
        </div>
        
        
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menuShare">
            <i class="icon icon-lg icon-share-alt"></i>
        </a>
        
    </div>
</header>
<header class="content-header post-header">

    <div class="container fade-scale">
        <h1 class="title">前端JS 图片压缩</h1>
        <h5 class="subtitle">
            
                <time datetime="2018-09-29T15:28:56.186Z" itemprop="datePublished" class="page-time">
  2018-09-29
</time>


            
        </h5>
    </div>

    


</header>


<div class="container body-wrap">
    
    <aside class="post-widget">
        <nav class="post-toc-wrap post-toc-shrink" id="post-toc">
            <h4>TOC</h4>
            <ol class="post-toc"><li class="post-toc-item post-toc-level-1"><a class="post-toc-link" href="#HTML"><span class="post-toc-number">1.</span> <span class="post-toc-text">HTML</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#index-html"><span class="post-toc-number">1.1.</span> <span class="post-toc-text">index.html</span></a></li></ol></li><li class="post-toc-item post-toc-level-1"><a class="post-toc-link" href="#JS"><span class="post-toc-number">2.</span> <span class="post-toc-text">JS</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#ImageResizer-js"><span class="post-toc-number">2.1.</span> <span class="post-toc-text">ImageResizer.js</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#index-js"><span class="post-toc-number">2.2.</span> <span class="post-toc-text">index.js</span></a></li></ol></li><li class="post-toc-item post-toc-level-1"><a class="post-toc-link" href="#参考资料"><span class="post-toc-number">3.</span> <span class="post-toc-text">参考资料</span></a></li></ol>
        </nav>
    </aside>


<article id="post-ImageResizer"
  class="post-article article-type-post fade" itemprop="blogPost">

    <div class="post-card">
        <h1 class="post-card-title">前端JS 图片压缩</h1>
        <div class="post-meta">
            <time class="post-time" title="2018-09-29 23:28:56" datetime="2018-09-29T15:28:56.186Z"  itemprop="datePublished">2018-09-29</time>

            


            
<span id="busuanzi_container_page_pv" title="文章总阅读量" style='display:none'>
    <i class="icon icon-eye icon-pr"></i><span id="busuanzi_value_page_pv"></span>
</span>


        </div>
        <div class="post-content" id="post-content" itemprop="postContent">
            <p>使用js原生上传图片，先将图片转为<strong>base64</strong>格式数据；然后初始化自定义对象<strong>ImageResizer</strong>，传入最大高宽、图片<strong>base64</strong>等参数；在<strong>ImageResizer</strong>中，先把图片对象写入到<strong>canvas</strong>中，然后根据最大高宽按原图片高宽比等比例缩小；最后返回缩小后的<strong>base64</strong>数据和<strong>canvas</strong>。</p>
<a id="more"></a>
<h1 id="HTML"><a href="#HTML" class="headerlink" title="HTML"></a>HTML</h1><h2 id="index-html"><a href="#index-html" class="headerlink" title="index.html"></a>index.html</h2><figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">input</span> <span class="attr">onchange</span>=<span class="string">"uploadBase64(this.files)"</span> <span class="attr">type</span>=<span class="string">"file"</span>&gt;</span></span><br></pre></td></tr></table></figure>
<h1 id="JS"><a href="#JS" class="headerlink" title="JS"></a>JS</h1><p>html页面引入ImageResizer.js、index.js。<strong>ImageResizer.js</strong>是方法类，修复了原文中会出现输出base64、canvas为空的问题，原因是图片太大未加载完就执行了图片压缩操作；<strong>index.js</strong>是页面具体操作脚本。</p>
<h2 id="ImageResizer-js"><a href="#ImageResizer-js" class="headerlink" title="ImageResizer.js"></a>ImageResizer.js</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 这是基于html5的前端图片工具，压缩工具。</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">var</span> ImageResizer = <span class="function"><span class="keyword">function</span> (<span class="params">opts</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> settings = &#123;</span><br><span class="line">        resizeMode: <span class="string">'auto'</span>,                    <span class="comment">//压缩模式，总共有三种  auto,width,height auto表示自动根据最大的宽度及高度等比压缩，width表示只根据宽度来判断是否需要等比例压缩，height类似。</span></span><br><span class="line">        dataSource: <span class="string">''</span>,                         <span class="comment">//数据源。数据源是指需要压缩的数据源，有三种类型，image图片元素，base64字符串，canvas对象，还有选择文件时候的file对象。。。</span></span><br><span class="line">        dataSourceType: <span class="string">'image'</span>,               <span class="comment">//image  base64 canvas</span></span><br><span class="line">        maxWidth: <span class="number">500</span>,                           <span class="comment">//允许的最大宽度</span></span><br><span class="line">        maxHeight: <span class="number">500</span>,                          <span class="comment">//允许的最大高度。</span></span><br><span class="line">        onTmpImgGenerate: <span class="function"><span class="keyword">function</span>(<span class="params">img</span>) </span>&#123;</span><br><span class="line">        &#125;,                                        <span class="comment">//当中间图片生成时候的执行方法。。这个时候请不要乱修改这图片，否则会打乱压缩后的结果。</span></span><br><span class="line">        success: <span class="function"><span class="keyword">function</span>(<span class="params">resizeImgBase64, canvas</span>)</span>&#123;</span><br><span class="line">        &#125;                                         <span class="comment">//压缩成功后图片的base64字符串数据。</span></span><br><span class="line">    &#125;;</span><br><span class="line">    <span class="keyword">var</span> appData = &#123;&#125;;</span><br><span class="line">    $.extend(settings, opts);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">var</span> innerTools = &#123;</span><br><span class="line">        getBase4FromImgFile: <span class="function"><span class="keyword">function</span>(<span class="params">file, callBack</span>) </span>&#123;</span><br><span class="line">            <span class="keyword">var</span> reader = <span class="keyword">new</span> FileReader();</span><br><span class="line">            reader.onload = <span class="function"><span class="keyword">function</span>(<span class="params">e</span>) </span>&#123;</span><br><span class="line">                <span class="keyword">var</span> base64Img = e.target.result;</span><br><span class="line">                <span class="keyword">if</span> (callBack) &#123;</span><br><span class="line">                    callBack(base64Img);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;;</span><br><span class="line">            reader.readAsDataURL(file);</span><br><span class="line">        &#125;,</span><br><span class="line"></span><br><span class="line">        <span class="comment">//--处理数据源。。。。将所有数据源都处理成为图片对象，方便处理。</span></span><br><span class="line">        getImgFromDataSource: <span class="function"><span class="keyword">function</span> (<span class="params">datasource, dataSourceType, callback</span>) </span>&#123;</span><br><span class="line">            <span class="keyword">var</span> _me = <span class="keyword">this</span>;</span><br><span class="line">            <span class="keyword">var</span> img1 = <span class="keyword">new</span> Image();</span><br><span class="line">            <span class="keyword">if</span> (dataSourceType == <span class="string">'img'</span> || dataSourceType == <span class="string">'image'</span>) &#123;</span><br><span class="line">                img1.src = $(datasource).attr(<span class="string">'src'</span>);</span><br><span class="line">                img1.onload = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">                    <span class="keyword">if</span> (callback) &#123;</span><br><span class="line">                        callback(img1);</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125; <span class="keyword">else</span> <span class="keyword">if</span> (dataSourceType == <span class="string">'base64'</span>) &#123;</span><br><span class="line">                img1.src = datasource;</span><br><span class="line">                img1.onload = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">                    <span class="keyword">if</span>(callback)&#123;</span><br><span class="line">                        callback(img1);</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;;</span><br><span class="line">            &#125; <span class="keyword">else</span> <span class="keyword">if</span> (dataSourceType == <span class="string">'canvas'</span>) &#123;</span><br><span class="line">                img1.src = datasource.toDataURL(<span class="string">'image/jpeg'</span>);</span><br><span class="line">                img1.onload = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">                    <span class="keyword">if</span> (callback) &#123;</span><br><span class="line">                        callback(img1);</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125; <span class="keyword">else</span> <span class="keyword">if</span> (dataSourceType == <span class="string">'file'</span>) &#123;</span><br><span class="line">                _me.getBase4FromImgFile(<span class="function"><span class="keyword">function</span> (<span class="params">base64str</span>) </span>&#123;</span><br><span class="line">                    img1.src = base64str;</span><br><span class="line">                    img1.onload = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">                        <span class="keyword">if</span> (callback) &#123;</span><br><span class="line">                            callback(img1);</span><br><span class="line">                        &#125;</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;,</span><br><span class="line"></span><br><span class="line">        <span class="comment">//计算图片的需要压缩的尺寸。当然，压缩模式，压缩限制直接从setting里面取出来。</span></span><br><span class="line">        getResizeSizeFromImg: <span class="function"><span class="keyword">function</span>(<span class="params">img</span>) </span>&#123;</span><br><span class="line">            <span class="keyword">var</span> _img_info = &#123;</span><br><span class="line">                w: $(img)[<span class="number">0</span>].naturalWidth,</span><br><span class="line">                h: $(img)[<span class="number">0</span>].naturalHeight</span><br><span class="line">            &#125;;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">var</span> _resize_info = &#123;</span><br><span class="line">                w: <span class="number">0</span>,</span><br><span class="line">                h: <span class="number">0</span></span><br><span class="line">            &#125;;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">if</span> (_img_info.w &lt;= settings.maxWidth &amp;&amp; _img_info.h &lt;= settings.maxHeight) &#123;</span><br><span class="line">                <span class="keyword">return</span> _img_info;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">if</span> (settings.resizeMode == <span class="string">'auto'</span>) &#123;</span><br><span class="line">                <span class="keyword">var</span> _percent_scale = <span class="built_in">parseFloat</span>(_img_info.w / _img_info.h);</span><br><span class="line">                <span class="keyword">var</span> _size1 = &#123;</span><br><span class="line">                    w: <span class="number">0</span>,</span><br><span class="line">                    h: <span class="number">0</span></span><br><span class="line">                &#125;;</span><br><span class="line">                <span class="keyword">var</span> _size_by_mw = &#123;</span><br><span class="line">                    w: settings.maxWidth,</span><br><span class="line">                    h: <span class="built_in">parseInt</span>(settings.maxWidth / _percent_scale)</span><br><span class="line">                &#125;;</span><br><span class="line">                <span class="keyword">var</span> _size_by_mh = &#123;</span><br><span class="line">                    w: <span class="built_in">parseInt</span>(settings.maxHeight * _percent_scale),</span><br><span class="line">                    h: settings.maxHeight</span><br><span class="line">                &#125;;</span><br><span class="line">                <span class="keyword">if</span>(_size_by_mw.h &lt;= settings.maxHeight)&#123;</span><br><span class="line">                    <span class="keyword">return</span> _size_by_mw;</span><br><span class="line">                &#125;</span><br><span class="line">                <span class="keyword">if</span>(_size_by_mh.w &lt;= settings.maxWidth)&#123;</span><br><span class="line">                    <span class="keyword">return</span> _size_by_mh;</span><br><span class="line">                &#125;</span><br><span class="line"></span><br><span class="line">                <span class="keyword">return</span> &#123;</span><br><span class="line">                    w: settings.maxWidth,</span><br><span class="line">                    h: settings.maxHeight</span><br><span class="line">                &#125;;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">if</span> (settings.resizeMode == <span class="string">'width'</span>) &#123;</span><br><span class="line">                <span class="keyword">if</span> (_img_info.w &lt;= settings.maxWidth) &#123;</span><br><span class="line">                    <span class="keyword">return</span> _img_info;</span><br><span class="line">                &#125;</span><br><span class="line">                <span class="keyword">var</span> _size_by_mw = &#123;</span><br><span class="line">                    w: settings.maxWidth,</span><br><span class="line">                    h: <span class="built_in">parseInt</span>(settings.maxWidth / _percent_scale)</span><br><span class="line">                &#125;;</span><br><span class="line">                <span class="keyword">return</span> _size_by_mw;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">if</span> (settings.resizeMode == <span class="string">'height'</span>) &#123;</span><br><span class="line">                <span class="keyword">if</span> (_img_info.h &lt;= settings.maxHeight) &#123;</span><br><span class="line">                    <span class="keyword">return</span> _img_info;</span><br><span class="line">                &#125;</span><br><span class="line">                <span class="keyword">var</span> _size_by_mh = &#123;</span><br><span class="line">                    w: <span class="built_in">parseInt</span>(settings.maxHeight * _percent_scale),</span><br><span class="line">                    h: settings.maxHeight</span><br><span class="line">                &#125;;</span><br><span class="line">                <span class="keyword">return</span> _size_by_mh;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;,</span><br><span class="line"></span><br><span class="line">        <span class="comment">//--将相关图片对象画到canvas里面去。</span></span><br><span class="line">        drawToCanvas: <span class="function"><span class="keyword">function</span>(<span class="params">img, theW, theH, realW, realH, callback</span>) </span>&#123;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">var</span> canvas = <span class="built_in">document</span>.createElement(<span class="string">'canvas'</span>);</span><br><span class="line">            canvas.width = theW;</span><br><span class="line">            canvas.height = theH;</span><br><span class="line">            <span class="keyword">var</span> ctx = canvas.getContext(<span class="string">'2d'</span>);</span><br><span class="line">            ctx.drawImage(img,</span><br><span class="line">                <span class="number">0</span>,<span class="comment">//sourceX,</span></span><br><span class="line">                <span class="number">0</span>,<span class="comment">//sourceY,</span></span><br><span class="line">                realW,<span class="comment">//sourceWidth,</span></span><br><span class="line">                realH,<span class="comment">//sourceHeight,</span></span><br><span class="line">                <span class="number">0</span>,<span class="comment">//destX,</span></span><br><span class="line">                <span class="number">0</span>,<span class="comment">//destY,</span></span><br><span class="line">                theW,<span class="comment">//destWidth,</span></span><br><span class="line">                theH<span class="comment">//destHeight</span></span><br><span class="line">            );</span><br><span class="line"></span><br><span class="line">            <span class="comment">//--获取base64字符串及canvas对象传给success函数。</span></span><br><span class="line">            <span class="keyword">var</span> base64str = canvas.toDataURL(<span class="string">'image/png'</span>);</span><br><span class="line">            <span class="keyword">if</span>(callback)&#123;</span><br><span class="line">                callback(base64str, canvas);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//--开始处理。</span></span><br><span class="line">    (<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        innerTools.getImgFromDataSource(settings.dataSource, settings.dataSourceType, <span class="function"><span class="keyword">function</span>(<span class="params">_tmp_img</span>) </span>&#123;</span><br><span class="line">            <span class="keyword">var</span> __tmpImg = _tmp_img;</span><br><span class="line">            settings.onTmpImgGenerate(_tmp_img);</span><br><span class="line"></span><br><span class="line">            <span class="comment">//--计算尺寸。</span></span><br><span class="line">            <span class="keyword">var</span> _limitSizeInfo = innerTools.getResizeSizeFromImg(__tmpImg);</span><br><span class="line">            <span class="keyword">var</span> _img_info = &#123;</span><br><span class="line">                w:$(__tmpImg)[<span class="number">0</span>].naturalWidth,</span><br><span class="line">                h:$(__tmpImg)[<span class="number">0</span>].naturalHeight</span><br><span class="line">            &#125;;</span><br><span class="line"></span><br><span class="line">            innerTools.drawToCanvas(__tmpImg, _limitSizeInfo.w, _limitSizeInfo.h, _img_info.w, _img_info.h, <span class="function"><span class="keyword">function</span>(<span class="params">base64str, canvas</span>)</span>&#123;</span><br><span class="line">                settings.success(base64str, canvas);</span><br><span class="line">            &#125;);</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;)();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">var</span> returnObject=&#123;</span><br><span class="line">    &#125;;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> returnObject;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">dataURLtoBlob</span>(<span class="params">dataurl</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> arr = dataurl.split(<span class="string">','</span>), mime = arr[<span class="number">0</span>].match(<span class="regexp">/:(.*?);/</span>)[<span class="number">1</span>],</span><br><span class="line">        bstr = atob(arr[<span class="number">1</span>]), n = bstr.length, u8arr = <span class="keyword">new</span> <span class="built_in">Uint8Array</span>(n);</span><br><span class="line">    <span class="keyword">while</span> (n--) &#123;</span><br><span class="line">        u8arr[n] = bstr.charCodeAt(n);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> Blob([u8arr], &#123;<span class="attr">type</span>:mime&#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="index-js"><a href="#index-js" class="headerlink" title="index.js"></a>index.js</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">uploadBase64</span>(<span class="params">files</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> file = files[<span class="number">0</span>];</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">if</span> (file.type.indexOf(<span class="string">'image'</span>) &gt;= <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="keyword">var</span> reader = <span class="keyword">new</span> FileReader();</span><br><span class="line">        </span><br><span class="line">        reader.onload = <span class="function"><span class="keyword">function</span>(<span class="params">e</span>) </span>&#123;</span><br><span class="line">            <span class="keyword">var</span> base64Img = e.target.result;</span><br><span class="line">            <span class="keyword">var</span> maxWidth = <span class="number">512</span>;</span><br><span class="line">            <span class="keyword">var</span> maxHeight = <span class="number">512</span>;</span><br><span class="line">            </span><br><span class="line">            ImageResizer(&#123;</span><br><span class="line">                resizeMode: <span class="string">'auto'</span>,</span><br><span class="line">                dataSource: base64Img,</span><br><span class="line">                dataSourceType: <span class="string">'base64'</span>,</span><br><span class="line">                maxWidth: maxWidth, <span class="comment">//允许的最大宽度</span></span><br><span class="line">                maxHeight: maxHeight, <span class="comment">//允许的最大高度。</span></span><br><span class="line">                onTmpImgGenerate: <span class="function"><span class="keyword">function</span>(<span class="params">img</span>)</span>&#123;</span><br><span class="line">                &#125;,</span><br><span class="line">                success: <span class="function"><span class="keyword">function</span> (<span class="params">resizeImgBase64, canvas</span>) </span>&#123;</span><br><span class="line">                    <span class="built_in">console</span>.log(resizeImgBase64);  <span class="comment">// 图片压缩后的base64</span></span><br><span class="line">                    <span class="built_in">console</span>.log(canvas);           <span class="comment">// 图片压缩后的画布</span></span><br><span class="line">                &#125;</span><br><span class="line">            &#125;);</span><br><span class="line">        &#125;;</span><br><span class="line">        reader.readAsDataURL(file);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h1 id="参考资料"><a href="#参考资料" class="headerlink" title="参考资料"></a>参考资料</h1><p>1.<a href="https://www.cnblogs.com/hbujt/p/5551549.html" target="_blank" rel="noopener">前端实现图片压缩上传</a></p>

        </div>

        <blockquote class="post-copyright">
    
    <div class="content">
        
<span class="post-time">
    最后更新时间：<time datetime="2018-09-29T15:28:56.187Z" itemprop="dateUpdated">2018-09-29 23:28:56</time>
</span><br>


        
        原始链接：<a href="/weblog/2018/09/29/ImageResizer/" target="_blank" rel="external">https://greg0566.gitee.io/weblog/2018/09/29/ImageResizer/</a>
        
    </div>
    
    <footer>
        <a href="https://greg0566.gitee.io/weblog">
            <img src="/weblog/img/head.jpg" alt="Greg Zhou">
            Greg Zhou
        </a>
    </footer>
</blockquote>

        
<div class="page-reward">
    <a id="rewardBtn" href="javascript:;" class="page-reward-btn waves-effect waves-circle waves-light">赏</a>
</div>



        <div class="post-footer">
            
	<ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/weblog/tags/HTML/">HTML</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/weblog/tags/jQuery/">jQuery</a></li></ul>


            
<div class="page-share-wrap">
    

<div class="page-share" id="pageShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=https://greg0566.gitee.io/weblog/2018/09/29/ImageResizer/&title=《前端JS 图片压缩》 — Greg's Blog&pic=https://greg0566.gitee.io/weblog/img/head.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=https://greg0566.gitee.io/weblog/2018/09/29/ImageResizer/&title=《前端JS 图片压缩》 — Greg's Blog&source=使用js原生上传图片，先将图片转为base64格式数据；然后初始化自定义对象ImageResizer，传入最大高宽、图片base64等参数；在ImageR..." data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=https://greg0566.gitee.io/weblog/2018/09/29/ImageResizer/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《前端JS 图片压缩》 — Greg's Blog&url=https://greg0566.gitee.io/weblog/2018/09/29/ImageResizer/&via=https://greg0566.gitee.io/weblog" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=https://greg0566.gitee.io/weblog/2018/09/29/ImageResizer/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>



    <a href="javascript:;" id="shareFab" class="page-share-fab waves-effect waves-circle">
        <i class="icon icon-share-alt icon-lg"></i>
    </a>
</div>



        </div>
    </div>

    
<nav class="post-nav flex-row flex-justify-between">
  
    <div class="waves-block waves-effect prev">
      <a href="/weblog/2018/09/30/webSocket/" id="post-prev" class="post-nav-link">
        <div class="tips"><i class="icon icon-angle-left icon-lg icon-pr"></i> Prev</div>
        <h4 class="title">node WebSocket通信</h4>
      </a>
    </div>
  

  
    <div class="waves-block waves-effect next">
      <a href="/weblog/2018/09/17/cas_4.0_deploy/" id="post-next" class="post-nav-link">
        <div class="tips">Next <i class="icon icon-angle-right icon-lg icon-pl"></i></div>
        <h4 class="title">CAS Server 4.0 部署</h4>
      </a>
    </div>
  
</nav>



    











    <!-- Valine Comments -->
    <div class="comments vcomment" id="comments"></div>
    <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
    <script src="//unpkg.com/valine@latest/dist/Valine.min.js"></script>
    <!-- Valine Comments script -->
    <script>
        var GUEST_INFO = ['nick','mail','link'];
        var guest_info = 'nick,mail'.split(',').filter(function(item){
          return GUEST_INFO.indexOf(item) > -1
        });
        new Valine({
            el: '#comments',
            notify: 'false' == 'true',
            verify: 'true' == 'true',
            appId: "8LYR57meeLmJoqq4dEX8OGyj-gzGzoHsz",
            appKey: "6GCR491vuixHmMep2r9xFrOc",
            avatar: "mm",
            placeholder: "说点什么吧~",
            guest_info: guest_info.length == 0 ? GUEST_INFO : guest_info,
            pageSize: "10"
        })
    </script>
    <!-- Valine Comments end -->







</article>

<div id="reward" class="page-modal reward-lay">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <h3 class="reward-title">
        <i class="icon icon-quote-left"></i>
        谢谢大爷~
        <i class="icon icon-quote-right"></i>
    </h3>
    <div class="reward-content">
        
        <div class="reward-code">
            <img id="rewardCode" src="/weblog/img/wechat.png" alt="打赏二维码">
        </div>
        
        <label class="reward-toggle">
            <input id="rewardToggle" type="checkbox" class="reward-toggle-check"
                data-wechat="/weblog/img/wechat.png" data-alipay="/weblog/img/alipay.png">
            <div class="reward-toggle-ctrol">
                <span class="reward-toggle-item wechat">微信</span>
                <span class="reward-toggle-label"></span>
                <span class="reward-toggle-item alipay">支付宝</span>
            </div>
        </label>
        
    </div>
</div>



</div>

        <footer class="footer">
    <div class="top">
        
<p>
    <span id="busuanzi_container_site_uv" style='display:none'>
        站点总访客数：<span id="busuanzi_value_site_uv"></span>
    </span>
    <span id="busuanzi_container_site_pv" style='display:none'>
        站点总访问量：<span id="busuanzi_value_site_pv"></span>
    </span>
</p>


        <p>
            
                <span><a href="/weblog/atom.xml" target="_blank" class="rss" title="rss"><i class="icon icon-lg icon-rss"></i></a></span>
            
            <span>博客内容遵循 <a rel="license" href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh">知识共享 署名 - 非商业性 - 相同方式共享 4.0 国际协议</a></span>
        </p>
    </div>
    <div class="bottom">
        <p><span>Greg Zhou &copy; 2018</span>
            <span>
                
                Power by <a href="http://hexo.io/" target="_blank">Hexo</a> Theme <a href="https://github.com/yscoder/hexo-theme-indigo" target="_blank">indigo</a>
            </span>
        </p>
    </div>
</footer>

    </main>
    <div class="mask" id="mask"></div>
<a href="javascript:;" id="gotop" class="waves-effect waves-circle waves-light"><span class="icon icon-lg icon-chevron-up"></span></a>



<div class="global-share" id="globalShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=https://greg0566.gitee.io/weblog/2018/09/29/ImageResizer/&title=《前端JS 图片压缩》 — Greg's Blog&pic=https://greg0566.gitee.io/weblog/img/head.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=https://greg0566.gitee.io/weblog/2018/09/29/ImageResizer/&title=《前端JS 图片压缩》 — Greg's Blog&source=使用js原生上传图片，先将图片转为base64格式数据；然后初始化自定义对象ImageResizer，传入最大高宽、图片base64等参数；在ImageR..." data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=https://greg0566.gitee.io/weblog/2018/09/29/ImageResizer/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《前端JS 图片压缩》 — Greg's Blog&url=https://greg0566.gitee.io/weblog/2018/09/29/ImageResizer/&via=https://greg0566.gitee.io/weblog" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=https://greg0566.gitee.io/weblog/2018/09/29/ImageResizer/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>


<div class="page-modal wx-share" id="wxShare">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <p>扫一扫，分享到微信</p>
    <img src="" alt="微信分享二维码">
</div>




    <script src="//cdn.bootcss.com/node-waves/0.7.4/waves.min.js"></script>
<script>
var BLOG = { ROOT: '/weblog/', SHARE: true, REWARD: true };


</script>

<script src="/weblog/js/main.min.js?v=1.7.2"></script>


<div class="search-panel" id="search-panel">
    <ul class="search-result" id="search-result"></ul>
</div>
<template id="search-tpl">
<li class="item">
    <a href="{path}" class="waves-block waves-effect">
        <div class="title ellipsis" title="{title}">{title}</div>
        <div class="flex-row flex-middle">
            <div class="tags ellipsis">
                {tags}
            </div>
            <time class="flex-col time">{date}</time>
        </div>
    </a>
</li>
</template>

<script src="/weblog/js/search.min.js?v=1.7.2" async></script>






<script async src="//dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>





</body>
</html>
